﻿using UnityEngine;

public class GenCubeByParam : MonoBehaviour
{
    public int count = 100;
    public Vector3 min = Vector3.zero;
    public Vector3 max = Vector3.one;
    public Material material;

    // 材质属性块
    private MaterialPropertyBlock _mpb;
    
    private void Start()
    {
        _mpb = new MaterialPropertyBlock();
        
        for (int i = 0; i < count; i++)
        {
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            var meshRenderer = go.GetComponent<MeshRenderer>();
            meshRenderer.sharedMaterial = material;
            go.transform.position = new Vector3(
                Random.Range(min.x, max.x),
                Random.Range(min.y, max.y),
                Random.Range(min.z, max.z)
            );
            
            // 设定每个对象自己的材质属性
            _mpb.SetColor("_Color", new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1.0f));
            _mpb.SetFloat("_Phi", Random.Range(-40f, 40f));
            // 关联到 Renderer 上，新设置的值会自动和当前对象进行关联
            meshRenderer.SetPropertyBlock(_mpb);
        }
    }
}
